package rd0910;
import fr.irstv.kmeans.DataGroup;
import ij.ImagePlus;

import java.awt.Color;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;


/**
 * 
 */

/**
 * @author Leo COLLET, Cedric TELEGONE, Ecole Centrale Nantes, 2010
 *
 */
public class SegmentDetection {

	public SegmentDetection(){
		
	}
	
	public static File run(File file) {
		String path = file.getPath();
		File output;

		HashMap<Integer,Color> colorMap = new HashMap<Integer,Color>(8); // Color map
		colorMap.put(0, Color.RED);
		colorMap.put(1, Color.BLUE);
		colorMap.put(2, Color.WHITE);
		colorMap.put(3, Color.CYAN);
		colorMap.put(4, Color.GREEN);
		colorMap.put(5, Color.MAGENTA);
		colorMap.put(6, Color.ORANGE);
		colorMap.put(7, Color.YELLOW);
		
		try {
			ImageSegment is = new ImageSegment(path, 800);
			is.getLargeConnectedEdges(false, 8);
			//Utils.getImageFromImageSegment(is);
			String[] splitPath = path.split("/");
			String fileBaseName;
			if (splitPath.length >= 1){
				fileBaseName = splitPath[splitPath.length - 1];
			} else {
				fileBaseName = path;
			}
			String fileBaseNameWithoutExtension = (fileBaseName != null) ? fileBaseName.substring(0,fileBaseName.indexOf('.')) : "";
			output = exportToXML(is, fileBaseNameWithoutExtension);
		} catch (NullPointerException npe){
			System.out.println("The file you tried to process can not be reached.");
			npe.printStackTrace();
			output = null;
		}
		return output;
		
	}
	
	public static File exportToXML(ImageSegment is, String path){
		PrintWriter file;
	    
	    try{
	    	file =  new PrintWriter(new BufferedWriter(new FileWriter(path + ".xml")));
	 	   
		    file.println("<?xml version=\"1.0\" ?>");
		    
		    file.println("<root>");
		    	file.println("<Epsilon Epsilon=\"40\"/>");
		    	file.println("<PointDeFuite>");
		    	file.println("<LES-SEGMENTS>");
		    	for (Iterator<Map.Entry<Integer, Vector<Segment>>> iter = is.finalSegmentMap.entrySet().iterator(); iter.hasNext();){
					Map.Entry<Integer, Vector<Segment>> ent = (Map.Entry<Integer, Vector<Segment>>) iter.next();
					for (int i=0; i<ent.getValue().size(); i++){
						file.print("<Coordonnees Segments-xp1=\"" + (float) ent.getValue().get(i).getStartPoint().getX() + "\" ");
						file.print("Segments-yp1=\"" + (float) ent.getValue().get(i).getStartPoint().getY() + "\" ");
						file.print("Segments-xp2=\"" + (float) ent.getValue().get(i).getEndPoint().getX() + "\" ");
						file.println("Segments-yp2=\"" + (float) ent.getValue().get(i).getEndPoint().getY() + "\"/>");
					}
				}
		    	file.println("</LES-SEGMENTS>");
		    	file.println("</PointDeFuite>");
		    file.println("</root>");
		    
		    file.close();
	    } catch (IOException ioe){
	    	System.out.println("Can not write on file " + path + ".xml");
	    	ioe.printStackTrace();
	    } catch (NullPointerException npe){
	    	System.out.println("Can not access to image segment map. Must be computed.");
	    	npe.printStackTrace();
	    }
	    File output = new File(path + ".xml");
	    return output;
	    
	}

	
	public static void main(String[] args){
		/**
		 * File chooser popup
		 */
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JFileChooser chooser = new JFileChooser();
	    JPGFilter filter = new JPGFilter();
	    chooser.setFileFilter(filter);
	    chooser.setMultiSelectionEnabled(true);

	    int returnVal = chooser.showOpenDialog(frame);
	    if(returnVal == JFileChooser.APPROVE_OPTION) {
	    	File[] files = chooser.getSelectedFiles();
	    	for (int i=0; i<files.length; i++){
	    		try{
	    			String path = files[i].getPath();
	    			ImagePlus imp = new ImagePlus(path);
	    			File f = new File(path);
	    			run(f);
	    			VanishingPoints vp= new VanishingPoints(f);
	    			DataGroup[] dg = vp.run(Utils.format(imp, 1000).getProcessor()); 
	    		} catch (OutOfMemoryError err){
	    			System.err.println("Error log: java.lang.OutOfMemoryError generated for image " + files[i].getName());
	    		}
	    	}   	
	    }
	}

}
